package com.xdf.ecommerce.feign;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author chanchaw
 * @create 2025-11-11 16:24
 */
@Slf4j
@Configuration
public class FeignConfig {
    @Bean
    public RequestInterceptor headerInterceptor(){
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            if(attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if(headerNames != null) {
                    while(headerNames.hasMoreElements()){
                        String s = headerNames.nextElement();
                        String header = request.getHeader(s);
                        // 把除了 content-length 之外的其他请求头都传递给下游服务提供者
                        // 不能把当前请求的 content-length 传递给下游服务提供者，两者的该属性的值可能不同
                        // 会导致下游服务一直无法返回或者请求响应数据被截断
                        if(!s.equalsIgnoreCase("content-length")){
                            template.header(s, header);// 这里的 template 就是 RestTemplate
                        }
                    }
                }
            }
        };
    }
}
